import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
	state:{
		gwc:{},
		sum:0
	},
	mutations:{
		//添加商品到购物车
		add(state, { id, product_name, price, spec, small_image}){
			let gwc = state.gwc
			if(gwc[id]){
				gwc[id]['num']++
				uni.showToast({
					title: '添加成功！'
				})
			}
			else{
				gwc[id] = {
					'id':id,
					'small_image':small_image,
					'product_name':product_name,
					'price':price,
					'spec':spec,
					'num':1
				}
				uni.showToast({
					title: '添加成功！'
				})
			}
			state.gwc = {...state.gwc}
		},
		//减少商品数量
		sub(state,item){
			let gwc = state.gwc
			gwc[item]['num']--
			state.gwc = {...state.gwc}
		},
		//增加商品数量
		zeng(state,item){
			let gwc = state.gwc
			gwc[item]['num']++
			state.gwc = {...state.gwc}
		},
		//删除商品
		deletes(state,item){
			delete state.gwc[item]
			state.gwc = {...state.gwc}
		},
		//购物车总价格
		sum(state){
			let arr = Object.values(state.gwc)
			state.sum = 0
			for(let i = 0;i < arr.length;i++){
				state.sum += (arr[i].price * arr[i].num)
			}
			state.sum = state.sum.toFixed(2)
		}
		
	}
})

export default store